package com.maotai.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class IPFactory {
	public static String HTTP_TYPE="BY";
	public static String ZM_IP_SOCKET_URL_200 = "http://webapi.http.zhimacangku.com/getip?num=200&type=2&pro=&city=0&yys=0&port=2&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=45&mr=2&regions=";
	public static String JL_IP_SOCKET_URL_200 = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty=199&time=2&pro=&city=&port=2&format=json&ss=5&css=&dt=1";
	public static String JL_IP_HTTP_URL_200 = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty=199&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=";
	public static String XM_IP_HTTP_URL_50="http://www.xiongmaodaili.com/xiongmao-web/api/glip?secret=599f1d47e9bd54e18dc95a2ad9881e0a&orderNo=GL201806061702158RwrArPj&count=50&isTxt=0";
	public static String ZM_IP_SOCKET_URL_1 = "http://webapi.http.zhimacangku.com/getip?num=1&type=2&pro=&city=0&yys=0&port=2&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=45&mr=2&regions=";
	public static String ZM_IP_HTTPS_URL_200 = "http://webapi.http.zhimacangku.com/getip?num=200&type=2&pro=&city=0&yys=0&port=11&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=45&mr=2&regions=";
	public static String BY_IP_HTTP_URL_200 = "http://baiyedaili.cn:8088/api.aspx?dno=maotai";
	
	public static String BY_IP_SOCKET_URL_200 = "http://baiyedaili.cn:8088/api.aspx?dno=maotai";
	
	public static String YN_IP_HTTP_URL_1000="http://ip.16yun.cn:817/myip/pl/20d1e352-2e38-4cd6-b8eb-f57296619140/?s=pmrypxdcoc&u=vipwangtao888&count=1000&format=json";
	
	public static JSONArray getIpAndPort() {
		JSONArray jArray = new JSONArray();
		if("BY".equals(HTTP_TYPE)){
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(BY_IP_HTTP_URL_200).build();
			// HttpClient

			String proxyIpAndPort = "localhost:8080";
			String[] strs = null;
			try {
				while (true) {
                    Response response = client.newCall(request).execute();//发送请求
                    proxyIpAndPort = response.body().string();
                    strs = proxyIpAndPort.split("\r\n");

					if (proxyIpAndPort.contains(":")) {
						break;
					}
					Thread.sleep(500);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if(strs!=null && strs.length>0){
				for(String str:strs){
					String[] ips = str.split(":");
					JSONObject jo = new JSONObject();
					jo.put("ip", ips[0]);
					jo.put("port", ips[1]);
					jArray.add(jo);
				}
			}
		}
		return jArray;
	}
	public static JSONObject getKdByUrl(String url) {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		JSONObject jObject = new JSONObject();
		// HttpClient
		HttpGet httpGet = new HttpGet(url);
		String proxyIpAndPort = "localhost:8080";
		while (true) {
			try {
				CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
				CloseableHttpResponse response = closeableHttpClient
						.execute(httpGet);
				// getEntity()
				HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null) {
					proxyIpAndPort = EntityUtils.toString(httpEntity, "UTF-8");
					System.out.println("response:" + proxyIpAndPort);
				}
				jObject = JSONObject.parseObject(proxyIpAndPort);
				if(proxyIpAndPort.contains("proxy")){
					if(jObject.getJSONArray("proxy").size()>0){
						break;
					}
				}
				if(proxyIpAndPort.contains("error_msg")){
					Thread.sleep(5000);
					continue;
				}
				if (jObject.getIntValue("code") == 0) {
					break;
				}
				
				Thread.sleep(500);
				closeableHttpClient.close();
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return jObject;
	}
	public static String[] getBYByUrl(String url) {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpGet httpGet = new HttpGet(url);
		String proxyIpAndPort = "localhost:8080";
		String[] strs = null;
		try {
			while (true) {
				CloseableHttpResponse response = closeableHttpClient
						.execute(httpGet);
				// getEntity()
				HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null) {
					proxyIpAndPort = EntityUtils.toString(httpEntity, "UTF-8");
					System.out.println("response:" + proxyIpAndPort);
					strs = proxyIpAndPort.split("\r\n");
				}
				if (proxyIpAndPort.contains(":")) {
					break;
				}
				Thread.sleep(500);
			}
//			CloseableHttpResponse response = closeableHttpClient
//						.execute(httpGet);
//			// getEntity()
//			HttpEntity httpEntity = response.getEntity();
//			if (httpEntity != null) {
//					proxyIpAndPort = EntityUtils.toString(httpEntity, "UTF-8");
//					System.out.println("response:" + proxyIpAndPort);
//					strs = proxyIpAndPort.split("\r\n");
//				Thread.sleep(500);
//			}
			closeableHttpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strs;
	}

	public static RequestConfig getKdRequestConfig(String ipAndPorts) {
		String[] ipAndPort = ipAndPorts.trim().split(":");
		if (ipAndPort == null || ipAndPort.length < 2) {
			return null;
		}
		/*
		 * { "msg": "", "code": 0, "data": { "count": 10, "proxy_list": [
		 * "124.172.117.189:19812", "219.133.31.120:26947",
		 * "183.237.194.145:28436", "183.62.172.50:23485",
		 * "163.125.157.243:17503", "183.57.42.79:26483",
		 * "202.103.150.70:17251", "182.254.129.124:15395",
		 * "58.251.132.181:20659", "112.95.241.76:21948" ] } }
		 */
		// 增加代理
		HttpHost proxy = new HttpHost(ipAndPort[0],
				Integer.parseInt(ipAndPort[1]));
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(300000).setConnectTimeout(300000)
				.setConnectionRequestTimeout(300000)
				.setProxy(proxy)
				.build();
		return requestConfig;
	}


	public static void main(String[] args) {

		while (true) {
			JSONObject jObject = IPFactory
					.getKdByUrl(IPFactory.ZM_IP_SOCKET_URL_1);
			JSONArray jArray = jObject.getJSONArray("data");
			JSONObject jj = (JSONObject) jArray.get(0);
			String ipAndPort = jj.getString("ip") + ":"
					+ jj.getIntValue("port");
			System.out.println(ipAndPort);
		}
	}
}
